package com.xuecheng.ucenter.service;

import com.xuecheng.framework.domain.ucenter.XcCompanyUser;
import com.xuecheng.framework.domain.ucenter.XcMenu;
import com.xuecheng.framework.domain.ucenter.XcUser;
import com.xuecheng.framework.domain.ucenter.ext.XcUserExt;
import com.xuecheng.ucenter.dao.XcCompanyUserRepository;
import com.xuecheng.ucenter.dao.XcMenuMapper;
import com.xuecheng.ucenter.dao.XcUserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhaoxiang
 * @version 1.0
 * @Date 2020/2/18 14:36
 */
@Service
public class XcUserService {

    @Autowired
    private XcUserRepository xcUserRepository;
    @Autowired
    private XcCompanyUserRepository xcCompanyUserRepository;
    @Autowired
    private XcMenuMapper xcMenuMapper;

    /**
     * 根据账户查询用户信息
     * @param username
     * @return
     */
    public XcUser findXcUserByUsername(String username){
        return xcUserRepository.findXcUserByUsername(username);
    }

    /**
     * 根据账号查询用户的信息，返回用户扩展信息
     * @param username
     * @return
     */
    public XcUserExt getUserExt(String username){
        XcUser xcUser = findXcUserByUsername(username);
        if(xcUser == null){
            return null;
        }
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser,xcUserExt);
        //用户id
        String userId = xcUserExt.getId();
        //查询用户所属公司
        XcCompanyUser xcCompanyUser = xcCompanyUserRepository.findByUserId(userId);
        //获取用户权限信息
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(userId);
        //不一定所有的用户都能取到companyId (学生用户就没有companyId   )
        String companyId = null;
        if (xcCompanyUser != null){
            companyId = xcCompanyUser.getCompanyId();
            xcUserExt.setCompanyId(companyId);
        }
        //设置权限
        xcUserExt.setPermissions(xcMenus);
        return xcUserExt;
    }
}
